package org.guajava.controller.tool;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.guajava.common.base.ResultInfo;
import org.guajava.framework.web.base.BaseController;
import org.guajava.service.ICodeService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ToolCodeController.java
 *
 * @Description:
 * @author: lishiming
 * @Date: 17:48 2019/1/8
 */
@Controller
@RequestMapping("/tool")
public class ToolCodeController extends BaseController {


    private String prefix = "tool/code";

    @Autowired
    private ICodeService iCodeService;

    @GetMapping("list")
    public String list()
    {
        return prefix + "/list";
    }
    @RequestMapping("/listData")
    @ResponseBody
    public ResultInfo<Map<String, Object>> listData(String tableName, Integer page, Integer limit){

        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableName);
        map.put("offset", (page - 1) * limit);
        map.put("limit", limit);
        List<Map<String, Object>> mapList = iCodeService.queryList(map);
        for (Map m : mapList){
            m.put("createTime", String.valueOf(m.get("createTime")).substring(0,19));
        }
        int total = iCodeService.queryTotal(map);

        return new ResultInfo(mapList, total);
    }

    /**
     * 生成代码
     */
    @RequestMapping("/generator")
    public void generator(String tables, HttpServletResponse response) throws IOException {
        byte[] data = iCodeService.generatorCode(tables.split(","));

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code-generator.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
